{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "application/vnd.databricks.v1+cell": {
          "cellMetadata": {},
          "inputWidgets": {},
          "nuid": "6fba2d42-ed99-4a03-8033-d479ce24d5dd",
          "showTitle": false,
          "title": ""
        },
        "id": "2vkOvTEsVaTA"
      },
      "source": [
        "# 使用 PEFT 进行提示微调\n",
        "\n",
        "_作者: [Pere Martra](https://github.com/peremartra)_\n",
        "\n",
        "\n",
        "在这个 notebook 中，我们将介绍如何使用 PEFT 库对预训练模型进行提示微调。\n",
        "\n",
        "要查看与 PEFT 兼容的完整模型列表，请参考他们的[文档](https://huggingface.co/docs/peft/main/en/index#supported-methods)。\n",
        "\n",
        "可以使用 PEFT 进行训练的模型示例包括 Bloom、Llama、GPT-J、GPT-2、BERT 等等。Hugging Face 正在努力将更多模型添加到库中。\n",
        "\n",
        "## 提示微调简要介绍\n",
        "\n",
        "这是一种用于模型的附加微调技术。这意味着我们不会修改原始模型的任何权重。你可能会想，那么我们将如何进行微调呢？好吧，我们将训练添加到模型中的额外层。这就是为什么它被称为附加技术。\n",
        "\n",
        "考虑到它是一种附加技术，并且它的名字是提示调整，似乎很明显我们将要添加和训练的层与提示有关。\n",
        "\n",
        "![Prompt_Tuning_Diagram](https://huggingface.co/datasets/huggingface/cookbook-images/resolve/main/Martra_Figure_5_Prompt_Tuning.jpg)\n",
        "\n",
        "我们通过使模型能够用其获取的知识增强提示的一部分来创建一种超提示。然而，提示的这部分不能翻译成自然语言。**这就好像我们已经掌握了用嵌入表达自己并生成高效提示的能力。**\n",
        "\n",
        "在每次训练周期中，唯一可以修改以最小化损失函数的权重是集成到提示中的权重。\n",
        "\n",
        "这种技术的主要结果是，要训练的参数数量确实很少。然而，我们遇到了第二个，也许更重要的结果，即**由于我们不修改预训练模型的权重，它不会改变其行为或忘记它以前学到的任何信息。**\n",
        "\n",
        "训练更快，更具成本效益。此外，我们可以训练各种模型，在推理时，我们只需要加载一个基础模型以及新的较小的训练模型，因为原始模型的权重没有被修改。\n",
        "\n",
        "## 我们将在 notebook 中做什么？\n",
        "\n",
        "我们将使用两个数据集训练两个不同的模型，每个数据集只使用 Bloom 家族的一个预训练模型。一个模型将使用提示数据集进行训练，而另一个模型将使用激励句子数据集进行训练。我们将比较两个模型在训练前后对同一问题的结果。\n",
        "\n",
        "此外，我们还将探讨如何只加载基础模型的一个副本到内存中，同时加载两个模型。\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "tZhdbTh-VaTA"
      },
      "source": [
        "## 加载 PEFT 库\n",
        "这个库包含了各种微调技术的 Hugging Face 实现，包括提示调整。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 41,
      "metadata": {
        "application/vnd.databricks.v1+cell": {
          "cellMetadata": {},
          "inputWidgets": {},
          "nuid": "d16bf5ec-888b-4c76-a655-193fd4cc8a36",
          "showTitle": false,
          "title": ""
        },
        "id": "JechhJhhVaTA"
      },
      "outputs": [],
      "source": [
        "!pip install -q peft==0.8.2"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 42,
      "metadata": {
        "id": "6CRxq5Z2WJ7C"
      },
      "outputs": [],
      "source": [
        "!pip install -q datasets==2.14.5"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GGbh426RVaTB"
      },
      "source": [
        "从 transformers 库中，我们导入必要的类来实例化模型和分词器。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 43,
      "metadata": {
        "application/vnd.databricks.v1+cell": {
          "cellMetadata": {},
          "inputWidgets": {},
          "nuid": "31738463-c9b0-431d-869e-1735e1e2f5c7",
          "showTitle": false,
          "title": ""
        },
        "id": "KWOEt-yOVaTB"
      },
      "outputs": [],
      "source": [
        "from transformers import AutoModelForCausalLM, AutoTokenizer"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6qYsnwjSVaTC"
      },
      "source": [
        "### 加载模型和分词器。\n",
        "\n",
        "Bloom 是使用 PEFT 库进行提示调整训练的可用模型中最小最智能的模型之一。你可以从 Bloom 家族中选择任何模型，我鼓励你至少尝试其中两个以观察它们之间的差异。\n",
        "\n",
        "我选择最小的模型以最小化训练时间并避免在 Colab 中出现内存问题。\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 44,
      "metadata": {
        "id": "MnqIhv2UVaTC"
      },
      "outputs": [],
      "source": [
        "model_name = \"bigscience/bloomz-560m\"\n",
        "#model_name=\"bigscience/bloom-1b1\"\n",
        "NUM_VIRTUAL_TOKENS = 4\n",
        "NUM_EPOCHS = 6"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 45,
      "metadata": {
        "id": "fSMu3qRsVaTC"
      },
      "outputs": [],
      "source": [
        "tokenizer = AutoTokenizer.from_pretrained(model_name)\n",
        "foundational_model = AutoModelForCausalLM.from_pretrained(\n",
        "    model_name,\n",
        "    trust_remote_code=True\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8W2fWhOnVaTC"
      },
      "source": [
        "## 使用预训练的 bloom 模型进行推理\n",
        "如果你想要实现更多样化和原创的生成，取消注释下面的 *model.generate* 中的参数：temperature、top_p 和 do_sample。\n",
        "\n",
        "在默认配置下，模型的响应在多次调用中保持一致。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 46,
      "metadata": {
        "id": "47j2D3WWVaTC"
      },
      "outputs": [],
      "source": [
        "#this function returns the outputs from the model received, and inputs.\n",
        "def get_outputs(model, inputs, max_new_tokens=100):\n",
        "    outputs = model.generate(\n",
        "        input_ids=inputs[\"input_ids\"],\n",
        "        attention_mask=inputs[\"attention_mask\"],\n",
        "        max_new_tokens=max_new_tokens,\n",
        "        #temperature=0.2,\n",
        "        #top_p=0.95,\n",
        "        #do_sample=True,\n",
        "        repetition_penalty=1.5, #Avoid repetition.\n",
        "        early_stopping=True, #The model can stop before reach the max_length\n",
        "        eos_token_id=tokenizer.eos_token_id\n",
        "    )\n",
        "    return outputs"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "application/vnd.databricks.v1+cell": {
          "cellMetadata": {},
          "inputWidgets": {},
          "nuid": "ca4d203a-5152-4947-ab34-cfd0b40a102a",
          "showTitle": false,
          "title": ""
        },
        "id": "kRLSfuo2VaTC"
      },
      "source": [
        "由于我们希望有两个不同的训练模型，我将创建两个不同的提示。\n",
        "\n",
        "第一个模型将使用包含提示的数据集进行训练，第二个模型将使用激励句子的数据集进行训练。\n",
        "\n",
        "第一个模型将收到提示 \"我希望你扮演一个励志教练。\"，第二个模型将收到提示 \"有两件对你来说很重要的事情：\"\n",
        "\n",
        "但首先，我要收集一些未经微调的模型的结果。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 47,
      "metadata": {
        "application/vnd.databricks.v1+cell": {
          "cellMetadata": {},
          "inputWidgets": {},
          "nuid": "1d4c80a9-4edd-4fcd-aef0-996f4da5cc02",
          "showTitle": false,
          "title": ""
        },
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "QvStaT7cVaTC",
        "outputId": "ab34b3cd-a849-4dff-b36d-bf25c9f55ce1"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[\"I want you to act as a motivational coach.  Don't be afraid of being challenged.\"]\n"
          ]
        }
      ],
      "source": [
        "input_prompt = tokenizer(\"I want you to act as a motivational coach. \", return_tensors=\"pt\")\n",
        "foundational_outputs_prompt = get_outputs(foundational_model, input_prompt, max_new_tokens=50)\n",
        "\n",
        "print(tokenizer.batch_decode(foundational_outputs_prompt, skip_special_tokens=True))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 69,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "1Xhm3jZMVaTD",
        "outputId": "305f0137-6a02-4e43-9c9d-2b4ecd377937"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "['There are two nice things that should matter to you: the price and quality of your product.']\n"
          ]
        }
      ],
      "source": [
        "input_sentences = tokenizer(\"There are two nice things that should matter to you:\", return_tensors=\"pt\")\n",
        "foundational_outputs_sentence = get_outputs(foundational_model, input_sentences, max_new_tokens=50)\n",
        "\n",
        "print(tokenizer.batch_decode(foundational_outputs_sentence, skip_special_tokens=True))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "application/vnd.databricks.v1+cell": {
          "cellMetadata": {},
          "inputWidgets": {},
          "nuid": "f438d43b-6b9f-445e-9df4-60ea09640764",
          "showTitle": false,
          "title": ""
        },
        "id": "OGbJTbRnVaTD"
      },
      "source": [
        "两个答案或多或少都是正确的。任何 Bloom 模型都是预先训练的，能够准确和合理地生成句子。让我们看看，在训练之后，响应是否相等或者生成得更加准确。\n",
        "\n",
        "## 准备数据集\n",
        "使用的数据集包括：\n",
        "* https://huggingface.co/datasets/fka/awesome-chatgpt-prompts\n",
        "* https://huggingface.co/datasets/Abirate/english_quotes\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 49,
      "metadata": {
        "id": "RD8H_LLaVaTD"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "#os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 50,
      "metadata": {
        "application/vnd.databricks.v1+cell": {
          "cellMetadata": {},
          "inputWidgets": {},
          "nuid": "2ed62b41-e3fa-4a41-a0a9-59f35a6904f9",
          "showTitle": false,
          "title": ""
        },
        "id": "xmAp_o4PVaTD"
      },
      "outputs": [],
      "source": [
        "from datasets import load_dataset\n",
        "\n",
        "dataset_prompt = \"fka/awesome-chatgpt-prompts\"\n",
        "\n",
        "#Create the Dataset to create prompts.\n",
        "data_prompt = load_dataset(dataset_prompt)\n",
        "data_prompt = data_prompt.map(lambda samples: tokenizer(samples[\"prompt\"]), batched=True)\n",
        "train_sample_prompt = data_prompt[\"train\"].select(range(50))\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 51,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 86
        },
        "id": "jNlOpGbqBgcu",
        "outputId": "3f8106b2-948b-4a7b-cf78-bd3fcc2f0338"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "Dataset({\n",
              "    features: ['act', 'prompt', 'input_ids', 'attention_mask'],\n",
              "    num_rows: 50\n",
              "})"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "display(train_sample_prompt)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 52,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "dZcOaE5CU658",
        "outputId": "fb8f5081-012b-4c37-ee1f-3aef2d0f54a7"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "{'act': ['Linux Terminal'], 'prompt': ['I want you to act as a linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output inside one unique code block, and nothing else. do not write explanations. do not type commands unless I instruct you to do so. when i need to tell you something in english, i will do so by putting text inside curly brackets {like this}. my first command is pwd'], 'input_ids': [[44, 4026, 1152, 427, 1769, 661, 267, 104105, 28434, 17, 473, 2152, 4105, 49123, 530, 1152, 2152, 57502, 1002, 3595, 368, 28434, 3403, 6460, 17, 473, 4026, 1152, 427, 3804, 57502, 1002, 368, 28434, 10014, 14652, 2592, 19826, 4400, 10973, 15, 530, 16915, 4384, 17, 727, 1130, 11602, 184637, 17, 727, 1130, 4105, 49123, 35262, 473, 32247, 1152, 427, 727, 1427, 17, 3262, 707, 3423, 427, 13485, 1152, 7747, 361, 170205, 15, 707, 2152, 727, 1427, 1331, 55385, 5484, 14652, 6291, 999, 117805, 731, 29726, 1119, 96, 17, 2670, 3968, 9361, 632, 269, 42512]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]}\n"
          ]
        }
      ],
      "source": [
        "print(train_sample_prompt[:1])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 53,
      "metadata": {
        "id": "WeM66LmEVaTD"
      },
      "outputs": [],
      "source": [
        "dataset_sentences = load_dataset(\"Abirate/english_quotes\")\n",
        "\n",
        "data_sentences = dataset_sentences.map(lambda samples: tokenizer(samples[\"quote\"]), batched=True)\n",
        "train_sample_sentences = data_sentences[\"train\"].select(range(25))\n",
        "train_sample_sentences = train_sample_sentences.remove_columns(['author', 'tags'])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 54,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 86
        },
        "id": "zUSG_M_nBp_E",
        "outputId": "faf36464-de24-4512-aace-c1ff8713c1d4"
      },
      "outputs": [
        {
          "data": {
            "text/plain": [
              "Dataset({\n",
              "    features: ['quote', 'input_ids', 'attention_mask'],\n",
              "    num_rows: 25\n",
              "})"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "display(train_sample_sentences)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "application/vnd.databricks.v1+cell": {
          "cellMetadata": {},
          "inputWidgets": {},
          "nuid": "b97381d4-5fe2-49d0-be5d-2fe3421edc5c",
          "showTitle": false,
          "title": ""
        },
        "id": "0-5mv1ZpVaTD"
      },
      "source": [
        "## 微调\n",
        "\n",
        "### PEFT 配置\n",
        "\n",
        "API 文档：\n",
        "https://huggingface.co/docs/peft/main/en/package_reference/tuners#peft.PromptTuningConfig\n",
        "\n",
        "我们可以对两个要训练的模型使用相同的配置。\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 55,
      "metadata": {
        "application/vnd.databricks.v1+cell": {
          "cellMetadata": {},
          "inputWidgets": {},
          "nuid": "6df8e1f1-be9e-42db-b4a4-6af7cd351004",
          "showTitle": false,
          "title": ""
        },
        "id": "sOg1Yh-oVaTD"
      },
      "outputs": [],
      "source": [
        "from peft import  get_peft_model, PromptTuningConfig, TaskType, PromptTuningInit\n",
        "\n",
        "generation_config = PromptTuningConfig(\n",
        "    task_type=TaskType.CAUSAL_LM, #This type indicates the model will generate text.\n",
        "    prompt_tuning_init=PromptTuningInit.RANDOM,  #The added virtual tokens are initializad with random numbers\n",
        "    num_virtual_tokens=NUM_VIRTUAL_TOKENS, #Number of virtual tokens to be added and trained.\n",
        "    tokenizer_name_or_path=model_name #The pre-trained model.\n",
        ")\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "an9KBtB1VaTD"
      },
      "source": [
        "### 创建两个提示调整模型。\n",
        "我们将使用相同的预训练模型和相同的配置来创建两个相同的提示调整模型。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 56,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "c_D8oDQZVaTD",
        "outputId": "6b46ca98-3f60-49c1-dab2-91259d6387af"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "trainable params: 4,096 || all params: 559,218,688 || trainable%: 0.0007324504863471229\n",
            "None\n"
          ]
        }
      ],
      "source": [
        "peft_model_prompt = get_peft_model(foundational_model, generation_config)\n",
        "print(peft_model_prompt.print_trainable_parameters())"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 57,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "IktYfj68VaTE",
        "outputId": "28fe03b7-4490-43ba-b913-4633e269737a"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "trainable params: 4,096 || all params: 559,218,688 || trainable%: 0.0007324504863471229\n",
            "None\n"
          ]
        }
      ],
      "source": [
        "peft_model_sentences = get_peft_model(foundational_model, generation_config)\n",
        "print(peft_model_sentences.print_trainable_parameters())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "application/vnd.databricks.v1+cell": {
          "cellMetadata": {},
          "inputWidgets": {},
          "nuid": "cff5bc33-8cfb-4144-8962-9c54362a7faa",
          "showTitle": false,
          "title": ""
        },
        "id": "i6WhJSUwVaTE"
      },
      "source": [
        "**太神奇了：你看到可训练参数的减少了吗？我们将要训练可用参数的 0.001%。**\n",
        "\n",
        "现在我们要创建训练参数，并且在这两次训练中我们将使用相同的配置。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 58,
      "metadata": {
        "id": "SJoznfzjVaTE"
      },
      "outputs": [],
      "source": [
        "from transformers import TrainingArguments\n",
        "def create_training_arguments(path, learning_rate=0.0035, epochs=6):\n",
        "    training_args = TrainingArguments(\n",
        "        output_dir=path, # Where the model predictions and checkpoints will be written\n",
        "        use_cpu=True, # This is necessary for CPU clusters.\n",
        "        auto_find_batch_size=True, # Find a suitable batch size that will fit into memory automatically\n",
        "        learning_rate= learning_rate, # Higher learning rate than full Fine-Tuning\n",
        "        num_train_epochs=epochs\n",
        "    )\n",
        "    return training_args"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 59,
      "metadata": {
        "application/vnd.databricks.v1+cell": {
          "cellMetadata": {},
          "inputWidgets": {},
          "nuid": "54b78a8f-81f0-44c0-b0bc-dcb14891715f",
          "showTitle": false,
          "title": ""
        },
        "id": "cb1j50DSVaTE"
      },
      "outputs": [],
      "source": [
        "\n",
        "import os\n",
        "\n",
        "working_dir = \"./\"\n",
        "\n",
        "#Is best to store the models in separate folders.\n",
        "#Create the name of the directories where to store the models.\n",
        "output_directory_prompt =  os.path.join(working_dir, \"peft_outputs_prompt\")\n",
        "output_directory_sentences = os.path.join(working_dir, \"peft_outputs_sentences\")\n",
        "\n",
        "#Just creating the directoris if not exist.\n",
        "if not os.path.exists(working_dir):\n",
        "    os.mkdir(working_dir)\n",
        "if not os.path.exists(output_directory_prompt):\n",
        "    os.mkdir(output_directory_prompt)\n",
        "if not os.path.exists(output_directory_sentences):\n",
        "    os.mkdir(output_directory_sentences)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OC5IhO9mVaTE"
      },
      "source": [
        "在创建 TrainingArguments 时，我们需要指明包含模型的目录。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 60,
      "metadata": {
        "id": "D4v4RSSeVaTE"
      },
      "outputs": [],
      "source": [
        "training_args_prompt = create_training_arguments(output_directory_prompt, 0.003, NUM_EPOCHS)\n",
        "training_args_sentences = create_training_arguments(output_directory_sentences, 0.003, NUM_EPOCHS)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "application/vnd.databricks.v1+cell": {
          "cellMetadata": {},
          "inputWidgets": {},
          "nuid": "c593deb6-5626-4fd9-89c2-2329e2f9b6e0",
          "showTitle": false,
          "title": ""
        },
        "id": "GdMfjk5RVaTE"
      },
      "source": [
        "## 训练\n",
        "\n",
        "我们将为每个要训练的模型创建一个 trainer 对象。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 61,
      "metadata": {
        "id": "uVAfNdEIVaTE"
      },
      "outputs": [],
      "source": [
        "from transformers import Trainer, DataCollatorForLanguageModeling\n",
        "def create_trainer(model, training_args, train_dataset):\n",
        "    trainer = Trainer(\n",
        "        model=model, # We pass in the PEFT version of the foundation model, bloomz-560M\n",
        "        args=training_args, #The args for the training.\n",
        "        train_dataset=train_dataset, #The dataset used to tyrain the model.\n",
        "        data_collator=DataCollatorForLanguageModeling(tokenizer, mlm=False) # mlm=False indicates not to use masked language modeling\n",
        "    )\n",
        "    return trainer\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 62,
      "metadata": {
        "application/vnd.databricks.v1+cell": {
          "cellMetadata": {},
          "inputWidgets": {},
          "nuid": "32e43bcf-23b2-46aa-9cf0-455b83ef4f38",
          "showTitle": false,
          "title": ""
        },
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 127
        },
        "id": "1Sz9BeFZVaTF",
        "outputId": "1b698470-209e-4001-fcbe-6fa8a2ac8707"
      },
      "outputs": [
        {
          "data": {
            "text/html": [
              "\n",
              "    <div>\n",
              "      \n",
              "      <progress value='42' max='42' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
              "      [42/42 11:23, Epoch 6/6]\n",
              "    </div>\n",
              "    <table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              " <tr style=\"text-align: left;\">\n",
              "      <th>Step</th>\n",
              "      <th>Training Loss</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "  </tbody>\n",
              "</table><p>"
            ],
            "text/plain": [
              "<IPython.core.display.HTML object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/plain": [
              "TrainOutput(global_step=42, training_loss=3.5800417945498513, metrics={'train_runtime': 703.2941, 'train_samples_per_second': 0.427, 'train_steps_per_second': 0.06, 'total_flos': 60957279240192.0, 'train_loss': 3.5800417945498513, 'epoch': 6.0})"
            ]
          },
          "execution_count": 62,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "#Training first model.\n",
        "trainer_prompt = create_trainer(peft_model_prompt, training_args_prompt, train_sample_prompt)\n",
        "trainer_prompt.train()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 63,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 127
        },
        "id": "afTotMckVaTF",
        "outputId": "15bed85d-17f5-4a49-d8d5-bae35e68d294"
      },
      "outputs": [
        {
          "data": {
            "text/html": [
              "\n",
              "    <div>\n",
              "      \n",
              "      <progress value='24' max='24' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
              "      [24/24 03:29, Epoch 6/6]\n",
              "    </div>\n",
              "    <table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              " <tr style=\"text-align: left;\">\n",
              "      <th>Step</th>\n",
              "      <th>Training Loss</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "  </tbody>\n",
              "</table><p>"
            ],
            "text/plain": [
              "<IPython.core.display.HTML object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/plain": [
              "TrainOutput(global_step=24, training_loss=4.4278310139973955, metrics={'train_runtime': 219.765, 'train_samples_per_second': 0.683, 'train_steps_per_second': 0.109, 'total_flos': 17825006936064.0, 'train_loss': 4.4278310139973955, 'epoch': 6.0})"
            ]
          },
          "execution_count": 63,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "#Training second model.\n",
        "trainer_sentences = create_trainer(peft_model_sentences, training_args_sentences, train_sample_sentences)\n",
        "trainer_sentences.train()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "z2Zsww_2VaTF"
      },
      "source": [
        "在不到 10 分钟的时间内（在 M1 Pro上的 CPU 时间），我们使用同一个基础模型训练了两个不同任务的模型。"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "application/vnd.databricks.v1+cell": {
          "cellMetadata": {},
          "inputWidgets": {},
          "nuid": "5a6c8daf-8248-458a-9f6f-14865b4fbd2e",
          "showTitle": false,
          "title": ""
        },
        "id": "s5k10HwoVaTG"
      },
      "source": [
        "## 保存模型\n",
        "我们将要保存模型。只要我们有创建它们的预训练模型在内存中，这些模型就可以使用了。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 64,
      "metadata": {
        "application/vnd.databricks.v1+cell": {
          "cellMetadata": {},
          "inputWidgets": {},
          "nuid": "409df5ce-e496-46d7-be2c-202a463cdc80",
          "showTitle": false,
          "title": ""
        },
        "id": "E3dn3PeMVaTG"
      },
      "outputs": [],
      "source": [
        "trainer_prompt.model.save_pretrained(output_directory_prompt)\n",
        "trainer_sentences.model.save_pretrained(output_directory_sentences)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "application/vnd.databricks.v1+cell": {
          "cellMetadata": {},
          "inputWidgets": {},
          "nuid": "fb14e3fd-bbf6-4d56-92c2-51bfe08de72a",
          "showTitle": false,
          "title": ""
        },
        "id": "rkUKpDDWVaTG"
      },
      "source": [
        "## 推理\n",
        "你可以从之前保存的路径加载模型，并根据我们的输入要求模型生成文本！"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 65,
      "metadata": {
        "application/vnd.databricks.v1+cell": {
          "cellMetadata": {},
          "inputWidgets": {},
          "nuid": "cc48af16-c117-4019-a31a-ce1c93cd21d4",
          "showTitle": false,
          "title": ""
        },
        "id": "dlqXXN8oVaTG"
      },
      "outputs": [],
      "source": [
        "from peft import PeftModel\n",
        "\n",
        "loaded_model_prompt = PeftModel.from_pretrained(foundational_model,\n",
        "                                         output_directory_prompt,\n",
        "                                         #device_map='auto',\n",
        "                                         is_trainable=False)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 66,
      "metadata": {
        "application/vnd.databricks.v1+cell": {
          "cellMetadata": {},
          "inputWidgets": {},
          "nuid": "6b44524b-2ac5-4e74-81e6-c406d4414e42",
          "showTitle": false,
          "title": ""
        },
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "-4jd3zCGVaTG",
        "outputId": "b55454f1-f1ed-444c-b107-698778406e6e"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "['I want you to act as a motivational coach.  You will be helping students learn how they can improve their performance in the classroom and at school.']\n"
          ]
        }
      ],
      "source": [
        "loaded_model_prompt_outputs = get_outputs(loaded_model_prompt, input_prompt)\n",
        "print(tokenizer.batch_decode(loaded_model_prompt_outputs, skip_special_tokens=True))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SHbeFTXjVaTG"
      },
      "source": [
        "如果我们比较两个答案，有些东西改变了。\n",
        "* ***预训练模型：*** *我希望你扮演一个激励教练。不要害怕被挑战。*\n",
        "* ***微调模型：*** *我希望你扮演一个激励教练。如果你感到焦虑，你可以使用这个方法。*\n",
        "\n",
        "我们必须记住，我们只训练了模型几分钟，但它们已经足够让我们得到更接近我们想要的结果的响应。\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 67,
      "metadata": {
        "id": "MuwAsq3uVaTG"
      },
      "outputs": [],
      "source": [
        "loaded_model_prompt.load_adapter(output_directory_sentences, adapter_name=\"quotes\")\n",
        "loaded_model_prompt.set_adapter(\"quotes\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 70,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "IQm--PWSVaTH",
        "outputId": "3e814a6a-a380-4f2c-f887-6852a9f51002"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "['There are two nice things that should matter to you: the weather and your health.']\n"
          ]
        }
      ],
      "source": [
        "loaded_model_sentences_outputs = get_outputs(loaded_model_prompt, input_sentences)\n",
        "print(tokenizer.batch_decode(loaded_model_sentences_outputs, skip_special_tokens=True))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "UnR8y9gwVaTH"
      },
      "source": [
        "对于第二个模型，我们得到了类似的结果。\n",
        "* **预训练模型：** *有两件对你来说很重要的事情：你的产品的价格和质量。*\n",
        "* **微调模型：** *有两件对你来说很重要的事情：天气和你的健康。*\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "B6TUjNtGVaTH"
      },
      "source": [
        "# 结论\n",
        "提示微调是一种惊人的技术，可以节省我们数小时的训练时间和大量的金钱。在这个 notebook 中，我们只用了几分钟就训练了两个模型，并且我们可以将两个模型都保存在内存中，为不同的客户提供服务。\n",
        "\n",
        "如果你想要尝试不同的组合和模型，这个 notebook 已经准备好使用 Bloom 家族中的另一个模型。\n",
        "\n",
        "你可以更改训练的轮数、虚拟 token 的数量和第三个单元格中的模型。然而，有许多配置需要更改。如果你正在寻找一个很好的练习，你可以用固定值替换虚拟 token 的随机初始化。\n",
        "\n",
        "*微调模型的响应可能在每次我们训练它们时都会有所不同。我粘贴了我的一次训练的结果，但实际结果可能会有所不同。*\n"
      ]
    }
  ],
  "metadata": {
    "application/vnd.databricks.v1+notebook": {
      "dashboards": [],
      "language": "python",
      "notebookMetadata": {
        "pythonIndentUnit": 2
      },
      "notebookName": "LLM 02 - Prompt Tuning with PEFT",
      "widgets": {}
    },
    "colab": {
      "machine_shape": "hm",
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3 (ipykernel)",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.11.4"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
